package server.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.interceptor.TransactionAspectSupport;
import server.config.exception.BizException;
import server.dao.FrmRoleDao;
import server.dao.UserSiteDao;
import server.dao.UsersDao;

import server.model.dto.UserDto;
import server.model.entity.FrmDiction;
import server.model.entity.UserSite;
import server.model.entity.Users;
import server.service.UserBlanceService;
import server.service.UserService;
import server.tool.tool.BeanUtil;
import server.tool.tool.EDcrypionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;


/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private FrmRoleDao frmRoleDao;
    @Autowired
    UserBlanceService userBlanceService;
    @Autowired
    UserSiteDao userSiteDao;

    @Override
    public Boolean checkStatus(String userId) {
        return usersDao.findById(userId).get().getStatus();
    }

    @Override
    @Transactional
    public Boolean createUser(UserDto userDto, Boolean parent) {
        if (parent) {
            checkParent(userDto.getParentId());
        }
        Users users = BeanUtil.convertToBean(userDto, Users.class);
        users.setPassword(EDcrypionUtils.shiroPassword(users.getPassword()));
        users.setActive(false);
        users.setRole(frmRoleDao.findById("2").get());
        users.setType("USER");
        if(users.getGrade()==null){
            users.setGrade(Users.Grade.GENERAL);
        }
        users.setInviteNum(0);
        users.setPerformance(0);
        users.setStatus(true);
        users.setSelfPerformance(0);
        users.setParentId(StringUtils.isNotBlank(userDto.getParentId()) ? userDto.getParentId() : "");
        users.setTree("");
        try {
            if (StringUtils.isNotBlank(userDto.getParentId())) {
                Users usParent = usersDao.findById(userDto.getParentId()).get();
                users.setParentName(usParent.getName());
                if (StringUtils.isNotBlank(usParent.getTree())) {
                    users.setTree(usParent.getTree() + "," + usParent.getId());
                    users.setTreeNum(users.getTree().length() - users.getTree().replaceAll(",", "").length());
                } else {
                    users.setTree(usParent.getId());
                    users.setTreeNum(users.getTree().length() - users.getTree().replaceAll(",", "").length());
                }
                usParent.setInviteNum(usParent.getInviteNum() + 1);
                usersDao.save(usParent);
                usersDao.flush();
            }
            users = usersDao.save(users);
            usersDao.flush();
            UserSite userSite = new UserSite();
            userSite.setUserId(users.getId());
            userSite.setSite("");
            userSite.setMobile("");
            userSite.setPeople("");
            userSite.setPick(true);
            userSite.setStatus(true);
            userSite.setIsDefault(false);
            userSiteDao.save(userSite);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BizException("手机号码或名称已被使用！");
        }
        userBlanceService.createBlance(users);
        return true;
    }

    private void checkParent(String parentId) {
        if (!Optional.ofNullable(usersDao.findById(parentId)).isPresent()) {
            throw new BizException(500, "邀请人不能为空！");
        }
    }

    @Override
    public List<Users> findBrother(Users users) {
        return usersDao.findByParentId(users.getParentId());
    }
}
